﻿#region License
/*
 *CopyRight (c) By Denuvead All Rights Reserved
 *CreateDate:
 *Info:
 */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SQLite;
using PriErp.Data;
using PriErp.Tools.Extensions;

namespace PriErp.Dal
{
	/// <summary>
	/// 用户信息
	/// </summary>
	[Serializable] 
	public class User
	{
		#region Model
		/// <summary>
		/// 用户ID
		/// </summary>
		public int UserID { get; set; }
		/// <summary>
		/// 姓名
		/// </summary>
		public string Name { get; set; }
		/// <summary>
		/// 称谓
		/// </summary>
		public string Title { get; set; }
		/// <summary>
		/// 密码
		/// </summary>
		public string PassWord { get; set; }
		/// <summary>
		/// 创建时间
		/// </summary>
		public DateTime CreateTime { get; set; }
		/// <summary>
		/// 上次登录时间
		/// </summary>
		public DateTime LastLoginTime { get; set; }
		/// <summary>
		/// 上次更改密码时间
		/// </summary>
		public DateTime LastChangePassWord { get; set; }
		/// <summary>
		/// 状态
		/// </summary>
		public UserStatus Status { get; set; }
		/// <summary>
		/// 权限
		/// </summary>
		public PowerType Master { get; set; }
		#endregion Model
	}
	public static class UserDAL
	{
		#region  BasicMethod
		/// <summary>
		/// 登录,登陆成功将插入登陆记录
		/// </summary>
		/// <param name="UserName">用户名</param>
		/// <param name="psw">密码</param>
		/// <returns>是否登录成功</returns>
		public static bool Login(string UserName, string PassWord)
		{
			string strSql = string.Format("INSERT INTO useractions (userid) SELECT userid from users WHERE name=@UserName and EXISTS (SELECT 1 FROM users WHERE name =@UserName and psw=@Psw and Status={0})", (int)UserStatus.Active);
			SQLiteParameter[] parms = {
					DbHelperSQLite.MakeParams("@UserName", DbType.String,20,UserName.TryTrim().ToLower()),
					DbHelperSQLite.MakeParams("@Psw", DbType.String,20,PassWord.TryTrim().ToLower())};
			return DbHelperSQLite.ExecuteSql(strSql, parms) > 0;
		}

		/// <summary>
		/// 获取登陆用户信息
		/// </summary>
		/// <param name="UserName">登陆用户名</param>
		/// <returns>返回用户信息</returns>
		public static User GetLoginUser(string UserName)
		{
			User user=null;
			string strSql = string.Format(@"select userid,master,LastLogin,ChangePwd from UserInfo where Name=@UserName",
							(int)ActionType.Login, (int)ActionType.ChangePassWord),
				name=UserName.TryTrim().ToLower();
			SQLiteParameter[] parameters = {
					DbHelperSQLite.MakeParams("@UserName", DbType.String,20,name)};
			SQLiteDataReader reader = DbHelperSQLite.ExecuteReader(strSql, parameters);
			if (reader.HasRows && reader.Read())
			{
				user = new User { 
					UserID = reader["userid"].ToStringEmpty().ToInt32(),
					Master =(PowerType) reader["master"].ToStringEmpty().ToInt32(), 
					Name = name,
					Status=UserStatus.Active,
					LastLoginTime = reader["LastLogin"].ToStringEmpty().ToDateTime(),
					LastChangePassWord = reader["LastLogin"].ToStringEmpty().ToDateTime()
				};
			}
			return user;
		}

		/// <summary>
		/// 是否存在该记录
		/// </summary>
		/// <param name="UserName">用户名</param>
		/// <returns>是否存在</returns>
		//public static bool Exists(string UserName)
		//{
		//    string strSql = "select count(1) from Users where Name=@UserName";
		//    SQLiteParameter[] parameters = {
		//            DbHelperSQLite.MakeParams("@UserName", DbType.String,20,UserName.TryTrim().ToLower())};
		//    return DbHelperSQLite.GetSingle(strSql, parameters).ToStringOrNull().ToInt32() > 0;
		//}

		/// <summary>
		/// 添加用户
		/// </summary>
		/// <param name="model">用户信息</param>
		/// <returns>是否成功添加</returns>
		public static bool Add(User model)
		{
			StringBuilder strSql = new StringBuilder();
			strSql.Append("insert into Users(");
			strSql.Append("Name,Title,Psw,Master)");
			strSql.Append(" values (");
			strSql.Append("@Name,@Title,@Psw,@Master)");
			SQLiteParameter[] parameters = {
					DbHelperSQLite.MakeParams("@Name", DbType.String,20,model.Name.TryTrim().ToLower()),
					DbHelperSQLite.MakeParams("@Title", DbType.String,20,model.Title),
					DbHelperSQLite.MakeParams("@Psw", DbType.String,20,model.PassWord.TryTrim().ToLower()),
					DbHelperSQLite.MakeParams("@Master", DbType.Boolean,0,model.Master)};
			return DbHelperSQLite.ExecuteSql(strSql.ToString(), parameters) > 0;
		}
		
		/// <summary>
		/// 更新用户信息
		/// </summary>
		/// <param name="model">需更新的用户</param>
		/// <returns>是否成功更新</returns>
		public static bool Update(User model)
		{
			StringBuilder strSql = new StringBuilder();
			strSql.Append("update Users set ");
			strSql.Append("Name=@Name,");
			strSql.Append("Title=@Title,");
			strSql.Append("Psw=@Psw,");
			strSql.Append("Status=@Status,");
			strSql.Append("Master=@Master");
			strSql.Append(" where UserID=@UserID");
			SQLiteParameter[] parameters = {
					DbHelperSQLite.MakeParams("@Name", DbType.String,20,model.Name.TryTrim().ToLower()),
					DbHelperSQLite.MakeParams("@Title", DbType.String,20,model.Title),
					DbHelperSQLite.MakeParams("@Psw", DbType.String,20,model.PassWord.TryTrim().ToLower()),
					DbHelperSQLite.MakeParams("@Status", DbType.Int32,0, (int)model.Status),
					DbHelperSQLite.MakeParams("@Master", DbType.Boolean,0,model.Master),
					new SQLiteParameter("@UserID", model.UserID)};
			return DbHelperSQLite.ExecuteSql(strSql.ToString(), parameters) > 0;
		}

		/// <summary>
		/// 获取用户总数
		/// </summary>
		/// <returns></returns>
		public static int GetUsersCount()
		{
			string sql = "select count(userid) from users";
			return DbHelperSQLite.GetSingle(sql).ToStringEmpty().ToInt32();
		}

		/// <summary>
		/// 获取所有用户信息
		/// </summary>
		/// <param name="PageIndex">当前页数</param>
		/// <param name="PageSize">当前页码</param>
		/// <param name="sortExp">排序规则(例如 Name desc)</param>
		/// <returns></returns>
		public static DataTable GetUsers(int PageIndex, int PageSize, string sortExp)
		{
			string sql = string.Format("select UserID,Name,Title,Psw,CreateTime,Status,Master,LastLogin,ChangePwd from userinfo order by {0} limit @offSet,@pageSize", sortExp);
			SQLiteParameter[] parms = {
									   new SQLiteParameter("@offSet",(PageIndex-1)*PageSize),
									   new SQLiteParameter("@pageSize",PageSize)
									  };
			return DbHelperSQLite.Query(sql, parms);
		}

		/// <summary>
		/// 删除用户,请处理1
		/// </summary>
		/// <param name="Ids">用户ID</param>
		/// <returns>是否删除成功</returns>
		public static bool Delete(List<int> Ids)
		{
			string strSql = string.Format("delete from Users where UserID in ({0});delete from useractions where userid in ({0})",  Ids.ToUninString(','));
			return DbHelperSQLite.ExecuteSql(strSql) > 0;
		}

		/// <summary>
		/// 禁用用户,请处理1
		/// </summary>
		/// <param name="Ids">用户ID</param>
		/// <returns>是否禁用成功</returns>
		public static bool Forbidden(List<int> Ids)
		{
			string UserIDlist = Ids.ToUninString(',');
			string  strSql = string.Format("update Users set Status={1} where UserID in ({0})", UserIDlist,(int)UserStatus.Forbidden);
			//清除用户记录 考虑是否需要抹除禁用用户的前期操作记录
			//strSql.AppendFormat(";delete from useractions where userid in ({0})", UserIDlist);
			return DbHelperSQLite.ExecuteSql(strSql) > 0;
		}

		/// <summary>
		/// 激活禁用账户
		/// </summary>
		/// <param name="Ids">用户ID</param>
		/// <returns>是否激活成功</returns>
		public static bool Active(List<int> Ids)
		{
			string UserIDlist = Ids.ToUninString(',');
			//更改用户状态 考虑是否需要对应Forbidden方法策略更改禁用用户创建时间
			string strSql =string.Format("update Users set Status={1} where UserID in ({0})", UserIDlist, (int)UserStatus.Active);
			return DbHelperSQLite.ExecuteSql(strSql) > 0;
		}

		#endregion  BasicMethod
	}
}
